package com.example.internet.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

public class ContactsClient {
    private static final SocketAddress ADDRESS = new
            InetSocketAddress("localhost", 8888);
    public static void main(String[] args) throws IOException {
        // 创建客⼾端 DatagramSocket
        DatagramSocket socket = new DatagramSocket();

        Request request = Request.newBuilder()
                .setName("张三")
                .setAge(20)
                .addPhone(Request.Phone.newBuilder()
                        .setNumber("1311111")
                        .build())
                .build();
        byte[] requestData = request.toByteArray();
        // byte[] requestData = {'h','e','l','l','o'};
        // 创建 request 数据报
        DatagramPacket requestPacket = new DatagramPacket(requestData,
                requestData.length, ADDRESS);
        // 发送 request 数据报
        socket.send(requestPacket);
        System.out.println("---->客户端发送成功！");

        // 创建 response 数据报，⽤于接收服务端返回的响应
        byte[] udpResponse = new byte[1024];
        DatagramPacket responsePacket = new DatagramPacket(udpResponse,
                udpResponse.length);
        // 接收 response 数据报
        socket.receive(responsePacket);
        // 获取有效的 response
        int length = BytesUtils.getValidLength(udpResponse);
        byte[] responseData = BytesUtils.subByte(udpResponse, 0, length);
        Response response =  Response.parseFrom(responseData);
        System.out.printf("---->接收到服务端返回的响应：%s", response.toString());

        // System.out.printf("---->接收到服务端返回的响应：%s", new String(responseData));
    }

}
